package com.yjt.termworks.fragment;


import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yjt.termworks.MainActivity;
import com.yjt.termworks.R;
import com.yjt.termworks.SendActivity;
import com.yjt.termworks.adapter.HomeCircleAdapter;
import com.yjt.termworks.entity.HomeCircle;
import com.yjt.termworks.sql.MyHelper;
import com.yjt.termworks.utils.ImageLoaderUtils;
import com.yjt.termworks.utils.SharePreferenceData;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {

    // 朋友圈信息
    View view = null;
    private List<HomeCircle> homeCircleArrayList;
    MyHelper myHelper;  // 数据库
//    private String baseImageUrl=R.string.baseImageUrl+"";
    private String baseImageUrl = "http://10.175.253.209:9002/images/userAvatar/";
    private HomeCircleAdapter adapter;
    private ImageView btn_send,iv_beauty,home_bg;
    private TextView userinfo_name;

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;

    public HomeFragment() {

    }


    public static HomeFragment newInstance(String param1, String param2) {
        HomeFragment fragment = new HomeFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_home, container, false);
        btn_send = view.findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toClickSend();
            }
        });


        myHelper = new MyHelper(view.getContext());    // 数据库
        // recycleVIew
        setData();
        setUserInfo();
        RecyclerView recyclerView = view.findViewById(R.id.recycle_home);
        recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));

        adapter = new HomeCircleAdapter(view.getContext(),homeCircleArrayList);
        recyclerView.setAdapter(adapter);
        // Inflate the layout for this fragment

        adapter.setOnItemClickListener(new HomeCircleAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View views, int position) {
                MyHelper myHelper = new MyHelper(view.getContext());
                SQLiteDatabase db = myHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                Integer num = homeCircleArrayList.size() - position  ;
                Log.d("==================>",num +"");

                Cursor cursor = db.rawQuery("select * from CIRCLE where _id = ?", new String[]{num+""});
                try {
                    if (cursor.moveToFirst()) {
                        String likeNum = cursor.getString(5);
                        int like = Integer.parseInt(likeNum);
                        like++;
                        EditText text = view.findViewById(R.id.comment_edit);
                        values.put("likeNum",like+"");
                        values.put("circleComment", text.getText().toString());
                        int b = db.update("CIRCLE", values, "_id=?", new String[]{num+""});
                        text.setText("");
                        // 自动刷新数据
//                        setData();
                        HomeFragment homeFragment = (HomeFragment) getFragmentManager().findFragmentById(R.id.menu_home);
                        if (homeFragment != null) {
                            homeFragment.refresh();
                        }
//                        adapter.notifyDataSetChanged();
                        Intent intent = new Intent(view.getContext(), MainActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.putExtra("flag", 0);
                        startActivity(intent);
                    } else {
                        Toast.makeText(view.getContext(), "查询失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(view.getContext(), "更新点赞数失败", Toast.LENGTH_SHORT).show();
                } finally {
                    if (cursor != null) {
                        cursor.close();
                    }
                    if (db != null && db.isOpen()) {
                        db.close();
                    }
                }
            }
        });

        return view;
    }

    public void refresh(){
        homeCircleArrayList = new ArrayList<>();
        setData();
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    private void setData(){

        RecyclerView recyclerView = view.findViewById(R.id.recycle_home);
        // 获取当前RecyclerView的布局参数
        ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams();
        // 设置新的高度值，单位为像素
        layoutParams.height = 750;
        // 将修改后的布局参数应用给RecyclerView
        recyclerView.setLayoutParams(layoutParams);
        homeCircleArrayList = null;
        SQLiteDatabase db = myHelper.getWritableDatabase();
        Cursor cursor = db.query("circle", null, null, null, null, null, "_id DESC");
        if(cursor.getCount() == 0){
            Toast.makeText(view.getContext(),"没有数据",Toast.LENGTH_SHORT).show();
            return;
        }
        homeCircleArrayList = new ArrayList<HomeCircle>();
        HomeCircle ci = null;

        while (cursor.moveToNext()){
//            for(int i = 0;i < cursor.getCount();i++){
                ci = new HomeCircle();
                ci.setUsername(cursor.getString(1));
                ci.setAvatar(baseImageUrl+cursor.getString(2));
                // 动态图片
                ArrayList<String> imgs = new ArrayList<>();
                if(cursor.getString(3) != "" && cursor.getString(3) != null){
                    String[] split = cursor.getString(3).toString().split(",");

                    for (String s : split) {
                        imgs.add(baseImageUrl+s);
                    }
                    ci.setCircleImagesList(imgs);
                }
                //
                ci.setCircleMsg(cursor.getString(4));
                ci.setLikeNum(cursor.getString(5));
                ci.setCircleComment(cursor.getString(6));
                homeCircleArrayList.add(ci);
//            }
        }
        cursor.close();
        db.close();

    }

    public void toClickSend(){
        Intent intent = new Intent();
        intent.setClass(view.getContext(), SendActivity.class);
        startActivity(intent);
    }

    public void setUserInfo(){
        userinfo_name = view.findViewById(R.id.userinfo_name);
        iv_beauty = view.findViewById(R.id.iv_beauty);
        home_bg = view.findViewById(R.id.home_bg);
         MyHelper myHelper;
         SQLiteDatabase db;
        myHelper = new MyHelper(view.getContext());
        db = myHelper.getWritableDatabase();

        Map<String, String> userInfo = SharePreferenceData.getUserData(view.getContext());
        String userPhone = userInfo.get("userName");
        Cursor cursor = db.rawQuery("select * from USER where phone = ?", new String[]{userPhone});
        try {
            if (cursor.moveToFirst()) {
                userinfo_name.setText(cursor.getString(1));
                ImageLoaderUtils.display(view.getContext(),iv_beauty,baseImageUrl+cursor.getString(4));
                ImageLoaderUtils.display(view.getContext(),home_bg,baseImageUrl+cursor.getString(5));
            } else {
                Toast.makeText(view.getContext(), "查询失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (db != null && db.isOpen()) {
                db.close();
            }
        }
    }


}
